import pandas as pd
import re
from enum import Enum, auto
from PIL import Image as PILImage
from utils import LOG
from typing import (
    TYPE_CHECKING,
    Any,
    Callable,
    Dict,
    Generator,
    List,
    Optional,
    Pattern,
    Tuple,
    Union,
)
class ContentType(Enum):
    TEXT = auto()
    TABLE = auto()
    IMAGE = auto()

class Content:
    def __init__(self, content_type, original, translation=None,font_size=None,is_bold=None,position=None,fontname="AAAAAE+LucidaGrande-Bold"):
        self.content_type = content_type
        self.original = original
        self.translation = translation
        self.status = False
        self.font_size = font_size
        self.is_bold = is_bold
        self.position = position
        self.fontname= fontname

    def set_translation(self, translation, status):
        if not self.check_translation_type(translation):
            raise ValueError(f"Invalid translation type. Expected {self.content_type}, but got {type(translation)}")
        self.translation = translation
        self.status = status

    def check_translation_type(self, translation):
        if self.content_type == ContentType.TEXT and isinstance(translation, str):
            return True
        elif self.content_type == ContentType.TABLE and isinstance(translation, list):
            return True
        elif self.content_type == ContentType.IMAGE and isinstance(translation, PILImage.Image):
            return True
        return False
    def __repr__(self):
        return f"Content(text={self.original}, size={self.font_size}, bold={self.is_bold}, position={self.position})"


class TableContent():
    def __init__(self, data: List, position=None):
        self.content_type=ContentType.TABLE
        self.position=position
        self.status = False
        self.data = data

        # Verify if the number of rows and columns in the data and DataFrame object match
        # if len(data) != len(df) or len(data[0]) != len(df.columns):
        #     raise ValueError("The number of rows and columns in the extracted table data and DataFrame object do not match.")
        
        #super().__init__(ContentType.TABLE, df)

    def set_translation(self, translation, status):
        if not isinstance(translation, str):
            raise ValueError(f"Invalid translation type. Expected str, but got {type(translation)}")

        try:
            # 使用from_markdown解析translation为TableContent对象
            translated_table = TableContent.from_markdown(translation)

            # 检查行数和列数是否匹配
            if len(translated_table) != len(self.data):
                raise ValueError("Row count mismatch between original table and translation.")
            for original_row, translated_row in zip(self.data, translated_table):
                if len(translated_row.cells) != len(original_row.cells):
                    raise ValueError("Column count mismatch between original table and translation.")

            # 更新原始表格中的内容为翻译后的内容
            for original_row, translated_row in zip(self.data, translated_table):
                for original_cell, translated_cell in zip(original_row.cells, translated_row.cells):
                    original_cell.translation = translated_cell.original
                    original_cell.status = status

            self.translation = translated_table
            self.status = status

        except Exception as e:
            LOG.error(f"An error occurred during table translation: {e}")
            self.translation = None
            self.status = False

    def __str__(self):
        if self.data is None or not self.data:
            return "TableContent is empty or not initialized."

        table_str = ""
        for row in self.data:
            row_str = " | ".join(cell.original for cell in row.cells)
            table_str += row_str + "\n"

        return table_str.strip()
    def iter_items(self, translated=False):
        target_df = self.translation if translated else self.original
        for row_idx, row in target_df.iterrows():
            for col_idx, item in enumerate(row):
                yield (row_idx, col_idx, item)

    def update_item(self, row_idx, col_idx, new_value, translated=False):
        target_df = self.translation if translated else self.original
        target_df.at[row_idx, col_idx] = new_value
        
    @staticmethod
    def from_markdown(markdown_table: str):
        # 分割Markdown表格行
        lines = markdown_table.strip().split('\n')
        rows = []

        # 解析每一行，跳过分隔符行
        for line in lines:
            if re.match(r"^\s*[-| ]+\s*$", line):  # 检查是否是分隔符行
                print(line)
                continue
            # 拆分单元格内容
            cells = [Cell(original=cell.strip()) for cell in line.split('|')]
            row = Row(cells=cells)
            rows.append(row)

        # 创建并返回TableContent对象
        return rows
    
   
    def generate_markdown_table(self, use_translation: bool = False) -> str:
        """
        生成Markdown表格，如果 use_translation 为 True，则使用翻译内容,翻译内容不存在则用原始内容，
        否则使用原始内容。

        :param use_translation: 是否使用翻译内容，默认为 False
        :return: Markdown 格式的表格字符串。
        """
        if not self.data:
            return "TableContent is empty or not initialized."

        # 创建Markdown表格的表头
        header_cells = self.data[0].cells
        header = " | ".join(
            cell.translation if use_translation and cell.translation else cell.original
            for cell in header_cells
        )
        separator = " | ".join(["---"] * len(header_cells))

        # 创建表格内容
        rows = []
        for row in self.data[1:]:
            row_str = " | ".join(
                cell.translation if use_translation and cell.translation else cell.original
                for cell in row.cells
            )
            rows.append(row_str)

        # 将表头、分隔符和表格内容组合成Markdown格式的表格
        markdown_table = f"{header}\n{separator}\n" + "\n".join(rows)
        return markdown_table   

    
class Cell:
    def __init__(self, original, translation=None, font_size=None, is_bold=None, width=None,heigth=None,fontname="AAAAAE+LucidaGrande-Bold"):
        """
        Cell类表示表格中的一个单元格
        :param original: 原始内容
        :param translation: 翻译内容（可选）
        :param font_size: 字体大小（可选）
        :param is_bold: 是否加粗（可选）
        :param width: 表格宽
        :param heigth: 表格高
        :param fontname: 字体名称
        """
        self.original = original
        self.translation = translation
        self.status = False
        self.font_size = font_size
        self.is_bold = is_bold
        self.width = width
        self.heigth = heigth
        self.fontname=fontname

class Row:
    def __init__(self, cells=None):
        """
        Row类表示表格中的一行，由多个Cell组成
        :param cells: Cell对象的列表
        """
        self.cells = cells if cells is not None else []

    def add_cell(self, cell):
        """
        添加一个Cell到当前Row中
        :param cell: Cell对象
        """
        self.cells.append(cell)

    def __iter__(self):
        """
        使Row对象可迭代，以便直接遍历行中的单元格
        """
        return iter(self.cells)

                    
                  
class ImageContent:
    def __init__(self, image_path,image_name, position,width=None,height=None):
        self.image_name = image_name
        self.image_path = image_path
        self.position = position
        self.width = width
        self.height= height
        self.status = False
        self.content_type=ContentType.IMAGE
        

    def __repr__(self):
        return f"ImageContent(image_path={self.image_path}, position={self.position})"
